<script setup>

import { ref, inject, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Plus, Delete, Refresh, Check } from '@element-plus/icons-vue'

const http = inject('$http'),
	tools = inject('$tools');

let list = ref([]),
	tree = ref([]),
	temp = ref({}),
	query = ref({ title: '', limit: 0 }),
	editForm = ref(),
	fetching = ref(false),
	submiting = ref(false),
	cascader_val = ref([]),
	showEditForm = ref(false);

const modelTemplate = {
	id: undefined, parent_id: 0, name: '', path_uri: '', method: '', description: '', order: 99
}

function resetTemp() {
	cascader_val.value = []
	temp.value = tools.deepCopy(modelTemplate)
}

let middleLayer = {};

function setTreeData(rows) {
	rows = tools.deepCopy(rows);

	middleLayer = {};
	for (let key in rows) {
		if (rows[key]['children']) {
			for (let lKey in rows[key]['children']) {
				const lItem = rows[key]['children'][lKey];
				middleLayer[lItem.id] = lItem.parent_id
				if(rows[key]['children'][lKey]['children']){
					delete rows[key]['children'][lKey]['children'];
				}
			}
		}
	}
	tree.value = rows;
	console.log(tree.value);
}

const fetch = async function () {
	fetching.value = true
	const res = await http.get('/rbac/permission', query.value);
	fetching.value = false
	if (res.code === 200) {
		list.value = res.data.rows;
		setTreeData(res.data.rows)
	}
	resetTemp()
}

const handleCreate = function () {
	resetTemp()
	showEditForm.value = true
	nextTick(() => {
		editForm.value.clearValidate()
	})
}

const handleEdit = function (row) {
	cascader_val.value = [];
	if(row.parent_id !== 1 && middleLayer[row.parent_id]){
		cascader_val.value.push(middleLayer[row.parent_id])
	}
	cascader_val.value.push(row.parent_id)
	temp.value = tools.deepCopy(row)
	showEditForm.value = true
	nextTick(() => {
		editForm.value.clearValidate()
	})
}

const handleAdd = function (row) {
	if (row.depth) {
		switch (row.depth) {
			case 0:
				cascader_val.value = [row.id]
				break
			case 1:
				cascader_val.value = [row.parent_id, row.id]
				break
			default:
				ElMessage({ message: '最多只能三层', type: 'warning' })
				return
		}
	} else {
		cascader_val.value = [row.id]
	}
	temp.value.parent_id = row.id
	showEditForm.value = true
	nextTick(() => {
		editForm.value.clearValidate()
	})
}

const handleDelete = async function (row) {
	ElMessageBox.confirm(`确定删除 '${row.name}' 吗？`, "提示", {
		confirmButtonText: "确定", cancelButtonText: "取消", type: "error",
	}).then(async () => {
		const res = await http.delete('/rbac/permission', { ids: row.id });
		if (res.code === 200) {
			ElMessage({ message: res.message, type: 'success' })
			fetch()
		}
	}).catch(() => { });
}

const submit = function () {
	if (submiting.value) return;
	editForm.value.validate(async (valid) => {
		if (!valid) return;
		submiting.value = true
		if (temp.value.parent_id === undefined) {
			temp.value.parent_id = 0
		}
		let res;
		if (temp.value.id) {
			res = await http.put('/rbac/permission', temp.value);
		} else {
			res = await http.post('/rbac/permission', temp.value);
		}
		submiting.value = false
		if (res && res.code === 200) {
			ElMessage({ message: res.message, type: 'success' })
			showEditForm.value = false
			fetch()
		}
	})
}

const changeParent = function (value) {
	temp.value.parent_id = value[value.length - 1]
}

const rules = {
	name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
	method: [{ required: true, message: '请选择请求方式', trigger: 'change' }],
	path_uri: [{ required: true, message: '请选输入路由', trigger: 'blur' }],
}

const methods = ref(['GET', 'POST', 'PUT', 'DELETE'])
const props = {
	value: 'id', label: 'name', children: 'children', checkStrictly: true
}

fetch();

</script>
<template>
	<h1 class="page-title">权限管理</h1>
	<el-form :inline="true" @submit.native.prevent="fetch" class="search-form">
		<el-form-item>
			<el-button type="primary" :icon="Refresh" :loading="fetching" :disabled="fetching"
				native-type="submit">刷新</el-button>
		</el-form-item>
		<el-form-item fixed="right">
			<el-button type="success" :icon="Plus" @click="handleCreate">
				添加
			</el-button>
		</el-form-item>
	</el-form>
	<div class="list-box">
		<el-table :data="list" :loading="fetching" style="width: 100%;margin-bottom: 20px;" row-key="id"
			:tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
			<el-table-column prop="name" label="权限名称" width="260" />
			<el-table-column prop="path_uri" label="路由" width="300" />
			<el-table-column prop="method" label="请求方式" width="100" />
			<el-table-column prop="order" label="排序" width="80" />
			<el-table-column prop="description" label="描述" />
			<el-table-column prop="created_at" label="创建时间" width="180" />
			<el-table-column label="操作">
				<template #default="scope">
					<el-button v-if="scope.row.depth < 2" type="success" size="small" :icon="Plus" @click="handleAdd(scope.row)" />
					<el-button type="primary" size="small" :icon="Edit" @click="handleEdit(scope.row)" />
					<el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row)" />
				</template>
			</el-table-column>
		</el-table>
	</div>
	<el-dialog :title="temp.id ? '编辑' : '添加'" width="500px" v-model="showEditForm" @close="resetTemp">
		<template #default>
			<el-form ref="editForm" :rules="rules" :model="temp" label-width="80px" style="margin:0 20px;">
				<el-row>
					<el-col :span="14">
						<el-form-item label="名称标识" prop="name">
							<el-input v-model="temp.name" placeholder="输入权限标识" />
						</el-form-item>
					</el-col>
					<el-col :span="10">
						<el-form-item label="请求方式" prop="method">
							<el-select v-model="temp.method" placeholder="请选择">
								<el-option v-for="item in methods" :key="item" :label="item" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="请求路由" prop="path_uri">
					<el-input v-model="temp.path_uri" placeholder="输入路由" />
				</el-form-item>
				<el-row>
					<el-col :span="17">
						<el-form-item label="上级权限" prop="parent_id">
							<el-cascader v-model="cascader_val" :options="tree" :props="props" placeholder="选择父级"
								@change="changeParent" :show-all-levels="false" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-form-item label="排序" prop="order">
							<el-input v-model="temp.order" placeholder="输入排序" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="详细描述" prop="description">
					<el-input v-model="temp.description" :autosize="{ minRows: 3, maxRows: 5 }" type="textarea"
						placeholder="菜单描述" />
				</el-form-item>
			</el-form>
		</template>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="showEditForm = false">取消</el-button>
				<el-button type="primary" :disabled="submiting" :loading="submiting" :icon="Check" @click="submit">
					保存
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>
